const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const reqResMiddleWare = require('./middleware/reqResMiddleware');
const errorHandlerMiddleWare = require('./middleware/errorHandlerMiddleware');
const routerList = require('./router');
const init = require('./config/init');
const app = express();

app.set('trust proxy', 1); // 只信任第一个代理
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
init();

app.use('*', (req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Expose-Headers', '*');
    next();
});

/**
 * 全局请求响应中间件
 */
app.use(reqResMiddleWare);
/**
 * 循环注册路由
 */
routerList.map(router => {
    app.use(router);
});
/**
 * 配置404请求
 */
app.use((req, res, next) => {
    res.json({
        status: 404,
        message: req.path + '接口不存在'
    });
});
app.use(errorHandlerMiddleWare());
app.listen(3000, () => {
    console.log('服务启动成功， 地址：http://127.0.0.1:3000');
});


